import { computed, ref, unref } from 'vue'
import { getBufferWithBlob } from '@/utils/file'
import {
  docTypes,
  excelTypes,
  imgTypes,
  pdfTypes,
  pptTypes,
  videoTypes,
} from '@/constant/file.constant'
import { transType } from '@/types/file'
import { useExcelWatermark } from './useExcelWatermark'
import { usePdfWatermark } from './usePdfWatermark'
import { useImgWatermark } from './useImgWatermark'
import { useVideoWatermark } from './useVideoWatermark'

const { excelWatermark, saveExcel } = useExcelWatermark()
const { pdfWatermark, savePdf } = usePdfWatermark()
const { imgWatermark, saveImg } = useImgWatermark()
const { videoWatermark, saveVideo } = useVideoWatermark()

export const useHandleWatermark = () => {
  const fileRes = ref()

  // 获取文件类型
  const fileType = computed(() => {
    const fileName = unref(fileRes)!.name
    const index = fileName.lastIndexOf('.')
    return fileName.slice(index, fileName.length)
  })

  /**
   * 添加水印
   */
  const watermarkFile = async () => {
    const fileBuffer = await getBufferWithBlob(unref(fileRes)!.raw as Blob)
    // ppt
    if (transType(pptTypes).includes(unref(fileType))) {
      // todo:
    }
    // word
    else if (transType(docTypes).includes(unref(fileType))) {
      // todo:
    }
    // pdf
    else if (transType(pdfTypes).includes(unref(fileType))) {
      await pdfWatermark(fileBuffer)
    }
    // excel
    else if (transType(excelTypes).includes(unref(fileType))) {
      await excelWatermark(fileBuffer)
    }
    // 图片
    else if (transType(imgTypes).includes(unref(fileType))) {
      await imgWatermark(fileBuffer)
    }
    // 视频
    else if (transType(videoTypes).includes(unref(fileType))) {
      await videoWatermark(unref(fileRes)?.raw?.path!)
    }
    return Promise.resolve()
  }

  /**
   * 保存文件
   */
  const saveFile = async () => {
    const fileName = unref(fileRes)!.name

    // ppt
    if (transType(pptTypes).includes(unref(fileType))) {
      // todo:
    }
    // word
    else if (transType(docTypes).includes(unref(fileType))) {
      // todo:
    }
    // pdf
    else if (transType(pdfTypes).includes(unref(fileType))) {
      await savePdf(fileName)
    }
    // excel
    else if (transType(excelTypes).includes(unref(fileType))) {
      await saveExcel(fileName)
    }
    // 图片
    else if (transType(imgTypes).includes(unref(fileType))) {
      await saveImg(fileName)
    }
    // 视频
    else if (transType(videoTypes).includes(unref(fileType))) {
      await saveVideo(fileName)
    }
    return Promise.resolve()
  }

  return {
    fileRes,
    watermarkFile,
    saveFile,
  }
}
